﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using log4net.Config;
using log4net.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Logging;
using Newtonsoft.Json;
using OAuth.EFCore.Interface;
using OAuth.EFCore.Model;
using OAuth.EFCore.Service;

namespace OAuth.EFCore.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration = configuration;
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
            repository = LogManager.CreateRepository("NETCoreRepository");
            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
        }

        public IConfiguration Configuration { get; }


        public static ILoggerRepository repository { get; set; }


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //这里就是填写数据库的链接字符串
            var connection = Configuration["EF:Connection"];
            services.AddDbContext<DataContext>(options => options.UseSqlServer(connection));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);



            #region "IdentityService4授权"
            services.AddMvcCore()
              .AddAuthorization()//添加身份验证服务
              .AddJsonFormatters();
            //AddAuthentication将身份验证服务添加到DI并配置"Bearer"为默认方案
            services.AddAuthentication("Bearer")
                    .AddIdentityServerAuthentication(options =>
                    {
                        options.Authority = "http://localhost:5000";//identifyServer服务地址
                        options.RequireHttpsMetadata = false;//是否使用https

                        options.ApiName = "api1";//进行身份验证的API资源的名称
                    });
            #endregion
            #region "注入"
            services.AddScoped<ILog>((s) => LogManager.GetLogger(repository.Name, typeof(Startup)));
            services.AddScoped<SSM01Service>();
            #endregion

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILog log)
        {
            //将身份验证中间件添加到管道中
            app.UseAuthentication();
            app.UseExceptionHandler(x => x.Run(async context => await ErrorEvent(context,log)));
            app.UseMvc();
        }

        public Task ErrorEvent(HttpContext context,ILog _log)
        {
            var feature = context.Features.Get<IExceptionHandlerFeature>();
            var error = feature?.Error;
            _log.Error("Global\\Error："+ error.Message, error.InnerException);
            return context.Response.WriteAsync(JsonConvert.SerializeObject(new { code = 444, msg = "系统未知异常，请联系管理员" }), Encoding.GetEncoding("utf-8"));
        }
    }
}
